<template>
  <div class="role">
    <search-page :searchFormConfig="searchFormConfig" />

    <page-content
      :pageContentConfig="pageTableConfig"
      pageName="role"
      @handleCreateData="handleCreateDataClick"
      @handleEditData="handleEditDataClick"
    ></page-content>

    <page-model
      ref="pageModelRef"
      :pageModelConfig="pageModelConfig"
      :defaultInfo="defaultInfo"
      :otherInfo="otherInfo"
      pageName="role"
    >
      <div class="model-tree">
        <el-tree
          ref="elTreeRef"
          :data="menusList"
          show-checkbox
          node-key="id"
          :props="{ children: 'children', label: 'name' }"
          @check="handleCheckChange"
        />
      </div>
    </page-model>
  </div>
</template>

<script lang="ts">
import { computed, defineComponent, nextTick, ref } from 'vue'
import { useStore } from '@/store'
import { ElTree } from 'element-plus'

import { pageTableConfig } from './config/pageContent.config'
import { searchFormConfig } from './config/search.config'
import { pageModelConfig } from './config/pageModel.config'

import { usePageModel } from '@/hooks/use-page-model'

import { menuMapLeafKeys } from '@/utils/map-menus'

export default defineComponent({
  name: 'role',
  components: {},
  setup() {
    const store = useStore()
    const menusList = computed(() => store.state.entireMenus)

    const elTreeRef = ref<InstanceType<typeof ElTree>>()
    const editCallBack = (item: any) => {
      const leafKeys = menuMapLeafKeys(item.menuList)
      nextTick(() => {
        elTreeRef.value?.setCheckedKeys(leafKeys, false)
      })
    }

    const [
      pageModelRef,
      defaultInfo,
      handleCreateDataClick,
      handleEditDataClick
    ] = usePageModel(undefined, editCallBack)

    const otherInfo = ref({})
    const handleCheckChange = (data1: any, data2: any) => {
      const { checkedKeys, halfCheckedKeys } = data2

      const menuList = [...checkedKeys, ...halfCheckedKeys]
      otherInfo.value = { menuList }
    }

    return {
      pageTableConfig,
      searchFormConfig,
      pageModelConfig,

      otherInfo,
      handleCheckChange,
      pageModelRef,
      defaultInfo,
      handleCreateDataClick,
      handleEditDataClick,
      menusList,
      elTreeRef
    }
  }
})
</script>

<style scoped>
.model-tree {
  margin-left: 30px;
}
</style>
